package easytalk.connectivity.googletalk;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.RosterListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;

import common.BodySet;
import common.Discussion;
import common.DiscussionSentence;
import common.DiscussionState;
import common.EasyChatEnvironment;
import common.EasyTalkException;
import common.Locutor;

import connection.AbstarctServerConnection;
import connection.ServerType;
import easytalk.connectivity.ILogWriter;
import easytalk.dialogs.ChatDialogManager;

public class GoogleTalkConnection extends AbstarctServerConnection {

	private XMPPConnection connection;
	private Roster roster;
	private String name;
	
	public GoogleTalkConnection() {
		super();
	}

	public XMPPConnection getConnection() {
		return connection;
	}

	public ILogWriter getLogWriter() {
		return logWriter;
	}

	@Override
	public void hookBodySet(BodySet set) throws Exception {
		roster = connection.getRoster();
		Locutor me = new Locutor(set, connection.getUser());
		logWriter.write("retrieving personal details", 80);
		set.setMe(me);
		me.setId(connection.getUser());
		me.setName("me");
		
		final List<Locutor> added = new ArrayList<Locutor>();
		for (RosterEntry r : roster.getEntries()) {
			Locutor locutor = set.createLocutor(r.getUser());
			added.add(locutor);
			locutor.setName(r.getName());
		logger.info(r.getUser());
			
		}
		connection.addPacketListener(new GoogleTalkPacketListener(null), new GoogleTalkPacketFilter(null));
		connection.getChatManager().addChatListener(new GoogleTalkChatManager());
		logWriter.write("connection done", 100);
		roster.addRosterListener(new RosterListener() {

			@Override
			public void entriesAdded(Collection<String> arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void entriesDeleted(Collection<String> arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void entriesUpdated(Collection<String> arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void presenceChanged(Presence arg0) {

			
				Locutor locutor;
				try {
					locutor = EasyChatEnvironment.getInstance()
							.getLocutorById(arg0.getFrom(), new GoogleTalkIdComparator());
				} catch (EasyTalkException e) {				
					e.printStackTrace();
					return;
				}
				
					locutor.setPresent(true);
					locutor.setStatus(GoogleDataAdapter.getLocatorStatus(arg0));
					EasyChatEnvironment.getInstance().update();
				
				ChatDialogManager.getInstance().updateDialogs();
			}

		});
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see easytalk.connectivity.IServerConnexion#login(java.lang.String,
	 * java.lang.String)
	 */
	public boolean login(String username, String password) throws Exception {
		ConnectionConfiguration config = new ConnectionConfiguration(
				Messages.getString("GoogleTalkConnection.0"), 5222, Messages.getString("GoogleTalkConnection.1")); //$NON-NLS-1$ //$NON-NLS-2$

		connection = new XMPPConnection(config);		
		this.config.setServerType(ServerType.GOOGLE_TALK);
		this.config.setUserName(username);
		this.config.setPassword(password);
		
		try {
			logWriter.write(Messages.getString("GoogleTalkConnection.2"),10); //$NON-NLS-1$
			connection.connect();
			logWriter.write(Messages.getString("GoogleTalkConnection.3"),20); //$NON-NLS-1$
			logWriter.write(Messages.getString("GoogleTalkConnection.4"),30); //$NON-NLS-1$

			connection.login(username, password);
			logWriter.write(Messages.getString("GoogleTalkConnection.5"),60); //$NON-NLS-1$
			this.name = Messages.getString("GoogleTalkConnection.6") + connection.getUser(); //$NON-NLS-1$
			return true;
			// EasyChatEnvironment.getInstance().addServerConnection(this);

			/*
			 * connection.addConnectionListener(new
			 * EasyTalkConnectionListener());
			 * connection.getChatManager().addChatListener(new
			 * EasyChatManagerListener(this));
			 * connection.addConnectionCreationListener(new
			 * EasyChatCreationListener()); connection.addPacketListener(new
			 * EasyPacketListner(this), new EasyPacketFilter());
			 */

		} catch (Exception e) {
			throw new Exception(e.getMessage());

		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see easytalk.connectivity.IServerConnexion#logout()
	 */
	public void logout() {
		connection.disconnect();
	}

	public void setConnection(XMPPConnection connection) {
		this.connection = connection;
	}

	public void setLogWriter(ILogWriter logWriter) {
		this.logWriter = logWriter;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	@Override
	public void createChat(String id) {
		
	}

	
	@Override
	public void sendMessage(String id, DiscussionSentence sentence) {
		Chat chat =  (Chat) sentence.getDiscussion().getData();
		if (chat == null)
			chat = connection.getChatManager().createChat(id, new GoogleTalkMessageListener());
		sentence.getDiscussion().setData(chat);
		
		try {
			chat.sendMessage(sentence.getContent());
		} catch (XMPPException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public void sendFastMessage(String id, String toBeSent) {	
		try {
				Locutor locutor = EasyChatEnvironment.getInstance().getLocutorById(id, new GoogleTalkIdComparator());	
				List<Discussion> discussions = EasyChatEnvironment.getInstance().FindDiscussionsWith(locutor);	
				if (discussions.size()>0) 
				{
					for (Discussion discussion : discussions) {
						if (discussion.getState() == DiscussionState.OPEN_DESCRETE) {
							Chat chat = (Chat) discussion.getData();
							chat.sendMessage(toBeSent);
							return;
						}
				 }
				}
				
					Chat chat = this.connection.getChatManager().createChat(id, null);
					System.out.println("creating chat : thrad id = " + chat.getThreadID());
					Discussion discussion = EasyChatEnvironment.getInstance().createDiscussion(chat.getThreadID());
					System.out.println("request complete");
					discussion.addLocutor(locutor);
					discussion.setState(DiscussionState.OPEN_DESCRETE);
					EasyChatEnvironment.getInstance().addDiscussion(discussion);
					chat.sendMessage(toBeSent);
						
		
		} catch (XMPPException e) {
			e.printStackTrace();
		} catch (EasyTalkException e) {
			e.printStackTrace();
		}
		
	}

}
